// 显示登录弹窗
function showLoginModal() {
    $.post(FromUrl,{type:'login',gid:gid},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
}

// 删除登录弹窗
function hideLoginModal(){
    document.querySelector('.login-modal').remove();
}

// 切换到手机号登录
function switchToPhoneLogin() {
    document.getElementById('accountLoginForm').style.display = 'none';
    document.getElementById('phoneLoginForm').style.display = 'block';
}

// 切换到账号登录
function switchToAccountLogin() {
    document.getElementById('phoneLoginForm').style.display = 'none';
    document.getElementById('accountLoginForm').style.display = 'block';
}

// 页面切换时清除定时器
function switchToAccountLogin() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
    document.getElementById('phoneLoginForm').style.display = 'none';
    document.getElementById('accountLoginForm').style.display = 'block';
}


let timer = null;
const COUNTDOWN_TIME = 60;

// 开始倒计时
function startCountdown(button) {
    let countdown = COUNTDOWN_TIME;
    button.disabled = true;
    button.textContent = `${countdown}秒后重试`;

    timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(timer);
            button.disabled = false;
            button.textContent = '获取验证码';
        } else {
            button.textContent = `${countdown}秒后重试`;
        }
    }, 1000);
}

// 发送短信验证码
function sendSmsCode() {
    const phone = document.getElementById('phone').value;

    // 简单的手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号');
        return;
    }
    
    // if (!imageCaptcha) {
    //     alert('请输入图片验证码');
    //     return;
    // }

    // 获取按钮元素
    const button = document.querySelector('.suffix-btn');
    
    const data = {
        phone:phone,
        // verify:imageCaptcha,
        gid:gid,
        cid:cid
    };
    // 这里添加发送短信验证码的逻辑
    // 假设这里是发送验证码的API调用
    $.post(sendSmsUrl,data,function(info){
        if(info.code==0) {
            layer.msg(info.msg,{time:2000});
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            // 发送成功后开始倒计时
            startCountdown(button);
        }else{
            // 其他错误
            layer.msg(info.msg || '发送失败，请重试', {time: 2000});
        }
    })

}

// 登录
function login(type) {
    const loading = document.querySelector('.loading');
    if (type === 'phone') {
        const phone = document.getElementById('phone').value;
        const smsCode = document.getElementById('smsCaptcha').value;
        
        const token = '';
        // 手机号登录逻辑
        const data = {
            phone:phone,
            code:smsCode,
            gid:gid,
            cid:cid
        };
        // 这里添加注册API调用
        $.post(phoneLoginUrl,data,function(info){
            console.log(info);
            if(info.code!=1) {
                layer.msg(info.msg,{time:2000});
                return false;
            }
            layer.msg(info.msg,{time:2000});
            hideLoginModal();
            //登录成功后，根据返回的info.game_url 重新加载iframe id="game-frame" 
            document.getElementById('aiqi-game-frame').src = info.data.game_url;
            //缓存token
            const url = new URL(window.location.href);
            url.searchParams.set("token", info.data.token);
            window.history.replaceState(null, '', url);
            token = info.data.token;
            // 登录成功后调用
            if(!info.data.age_status || info.data.age_status == 0){
                showAgeModal();
            }
            if(info.data.is_fcm==1){
                showLoginOutModal();
            }
            showFloatBall();
            loading.style.display = 'none';
            document.getElementById('aiqi-game-frame').style.display = 'block';
        })

        // 登录成功后保存手机号
        savePhoneToLocal(phone);
    } else {
        const account = document.getElementById('account').value;
        const password = document.getElementById('password').value;
        // 账号登录逻辑
        const data = {
            account:account,
            password:password,
            gid:gid,
            cid:cid
        };
        // 这里添加注册API调用
        $.post(accountLoginUrl,data,function(info){
            console.log(info.code);
            if(info.code!=1) {
                layer.msg(info.msg,{time:2000});
                return false;
            }
            layer.msg(info.msg,{time:2000});
            hideLoginModal();
            //登录成功后，根据返回的info.game_url 重新加载iframe id="game-frame" 
            document.getElementById('game-frame').src = info.data.game_url;
            //缓存token
            const url = new URL(window.location.href);
            url.searchParams.set("token", info.data.token);
            window.history.replaceState(null, '', url);
            token = info.data.token;
            // 登录成功后调用
            if(!info.data.age_status || info.data.age_status == 0){
                showAgeModal();
            }
            if(info.data.is_fcm==1){
                showLoginOutModal();
            }
            showFloatBall();
            loading.style.display = 'none';
            document.getElementById('game-frame').style.display = 'block';

        })

        // 登录成功后保存账号和密码
        saveAccountToLocal(account, password);
    }
    // 福利弹窗 登录成功后，延时2秒显示
    setTimeout(() => {
        shouyeArticle(0,1);
    }, 2000);
    //  高德数据上报 定时发送心跳包（每20秒）
    uploadLoginTime = setInterval(() => {
        // 获取当前URL的查询参数
        const urlParams = new URLSearchParams(window.location.search);
        const rp_token = urlParams.get('rp_token');
        // 这里添加修改密码API调用
        const data = {
            uid: uid,
            gid: gid,
            cid: cid,
            rp_token: rp_token,
            token: token,
        };
        $.post(uploadLoginTimeUrl, data, function(info) {
            console.log("数据上报返回:",info);
        });
    }, 5000);
}

function showAgeModal(){
    $.post(FromUrl,{type:'user_auth',gid:gid},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
}


function hideAgeModal(){
    const AgeModal = document.getElementById('Auth_user');
    if (AgeModal) {
        AgeModal.remove();
    }
}

function player_auth(){
    const name = document.getElementById('name').value;
    const idnum = document.getElementById('idnum').value;
    if(!name){
        layer.msg('请输入姓名',{time:2000});
        return false;
    }
    // 中文姓名正则（包括少数民族姓名中的·）
    const chineseNameRegex = /^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$/;
    if (!chineseNameRegex.test(name)) {
        layer.msg('请输入有效的中文姓名', {time: 2000});
        return false;
    }

    if(!idnum){
        layer.msg('请输入身份证号',{time:2000});
        return false;
    }
    // 身份证号正则（18位，最后一位可能是X）
    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
    if (!idCardRegex.test(idnum)) {
        layer.msg('请输入有效的18位身份证号', {time: 2000});
        return false;
    }

    // 验证年龄（根据身份证号计算）
    if (!validateAgeFromID(idnum)) {
        layer.msg('身份证号中的年龄信息无效', {time: 2000});
        return false;
    }

    // 手机号登录逻辑
    const data = {
        name:name,
        idnum:idnum,
        gid:gid,
        cid:cid,
        token:token
    };
    $.post(playerAuthUrl,data,function(result) {
        if(result.code == 1){
            layer.msg(result.msg,{time:2000});
            hideAgeModal();
        }else{
            layer.msg(result.msg,{time:2000});
        }
    });

}

function wx_login(code){
    const data = {
        code:code,
        gid:gid,
        cid:cid
    };
    // 这里添加注册API调用
    $.post(wxLoginUrl,data,function(info){
        console.log(info);
        if(info.code!=1) {
            layer.msg(info.msg,{time:2000});
            return false;
        }
        layer.msg(info.msg,{time:2000});
        hideLoginModal();
        //登录成功后，根据返回的info.game_url 重新加载iframe id="game-frame"
        document.getElementById('aiqi-game-frame').src = info.data.game_url;
        //缓存token
        const url = new URL(window.location.href);
        url.searchParams.set("token", info.data.token);
        window.history.replaceState(null, '', url);
        token = info.data.token;
        // 登录成功后调用
        showFloatBall();
        loading.style.display = 'none';
        document.getElementById('aiqi-game-frame').style.display = 'block';
        // 福利弹窗
        shouyeArticle(0,1);
    })
}

function showLoginOutModal(){
    const LoginOutModal = document.getElementById('player_loginout');
    if (!LoginOutModal) {
        $.post(FromUrl,{type:'player_loginout',gid:gid},function(html) {
            document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
        });
    }

}

function hideLoginOutModal(){
    const LoginOutModal = document.getElementById('player_loginout');
    if (LoginOutModal) {
        LoginOutModal.remove();
    }
}